package com.itheima.reggie.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.UserDto;
import com.itheima.reggie.entity.Employee;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")//登录校验拦截所有请求。交给spring管理，在启动类上方加注解@ServletComponentScan
public class CheckLoginFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //可以放行的资源
        String[] urls = {
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/login",
                "/user/sendMsg"
        };
        boolean check = check(urls, request.getRequestURI());
        //路径匹配，放行
        if (check){
            chain.doFilter(servletRequest, servletResponse);
            return;//不执行后续逻辑
        }
        //不匹配检查是否登录
        Object employee = request.getSession().getAttribute("employee");
        if(employee != null){
            BaseContext.setCurrentId(((Employee)employee).getId());
            chain.doFilter(servletRequest, servletResponse);
            return;
        }
        //不匹配检查是否登录
        Object user = request.getSession().getAttribute("user");
        if(user != null){
            BaseContext.setCurrentId(((UserDto)user).getId());
            chain.doFilter(servletRequest, servletResponse);
            return;
        }


        //不满足条件，按照前端要求返回要求的json数据
        response.setContentType("text/json;charset=utf-8");//设置响应的格式
        R<String> r = R.error("NOTLOGIN");
        String jsonStr = new ObjectMapper().writeValueAsString(r);
        response.getWriter().write(jsonStr);//响应json数据


    }
    //创建spring为我们提供的路径匹配器
    AntPathMatcher pathMatcher = new AntPathMatcher();
    //写一个方法匹配路径
    public boolean check(String[] urls,String requestUrI){
        for (String url : urls) {
            boolean match = pathMatcher.match(url, requestUrI);
            if (match){
                return true;
            }
        }
        return false;
    }
}
